﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace MainUI
{
    public partial class MainWindow : Window
    {
        // 声明一个静态变量来保存 HttpListener 实例
        private static HttpListener _httpListener;

        // 创建并启动 HTTP 服务器（仅在第一次调用时执行）
        private bool EnsureHttpServerRunning(string htmlPath, string imagesDirectory)
        {
            // 如果服务器已经在运行，直接返回 true
            if (_httpListener != null && _httpListener.IsListening)
            {
                return true;
            }

            try
            {
                // 创建一个简单的 HTTP 服务器
                _httpListener = new HttpListener();
                _httpListener.Prefixes.Add("http://localhost:8000/"); // 监听本地的 8000 端口
                _httpListener.Start();

                // MessageBox.Show("HTTP 服务器已启动，监听地址：http://localhost:8000/", "服务器启动", MessageBoxButton.OK, MessageBoxImage.Information);

                // 启动一个线程来处理 HTTP 请求
                ThreadPool.QueueUserWorkItem((o) =>
                {
                    try
                    {
                        while (_httpListener.IsListening)
                        {
                            HttpListenerContext context = _httpListener.GetContext();
                            HttpListenerRequest request = context.Request;
                            HttpListenerResponse response = context.Response;

                            try
                            {
                                string requestPath = request.Url.AbsolutePath;

                                // 处理根路径，返回 HTML 文件
                                if (requestPath == "/" || requestPath.EndsWith(".html"))
                                {
                                    string responseString = File.ReadAllText(htmlPath);
                                    byte[] buffer = Encoding.UTF8.GetBytes(responseString);
                                    response.ContentLength64 = buffer.Length;
                                    response.ContentType = "text/html";
                                    response.OutputStream.Write(buffer, 0, buffer.Length);
                                }
                                // 处理图片请求
                                else if (requestPath.StartsWith("/images/"))
                                {
                                    // 提取图片文件名（移除 /images/ 前缀）
                                    string fileName = requestPath.Substring(8);
                                    string imagePath = Path.Combine(imagesDirectory, fileName);

                                    if (File.Exists(imagePath))
                                    {
                                        // 根据文件扩展名确定 MIME 类型
                                        string mimeType = GetMimeType(Path.GetExtension(imagePath));
                                        response.ContentType = mimeType;

                                        // 读取图片文件并返回
                                        byte[] buffer = File.ReadAllBytes(imagePath);
                                        response.ContentLength64 = buffer.Length;
                                        response.OutputStream.Write(buffer, 0, buffer.Length);
                                    }
                                    else
                                    {
                                        response.StatusCode = 404; // 文件不存在
                                    }
                                }
                                else
                                {
                                    response.StatusCode = 404; // 未处理的路径返回 404
                                }
                            }
                            catch (Exception ex)
                            {
                                response.StatusCode = 500; // 服务器内部错误
                                byte[] buffer = Encoding.UTF8.GetBytes($"Error: {ex.Message}");
                                response.ContentLength64 = buffer.Length;
                                response.ContentType = "text/plain";
                                response.OutputStream.Write(buffer, 0, buffer.Length);
                            }
                            finally
                            {
                                response.OutputStream.Close();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // 使用 Dispatcher 确保在 UI 线程上显示消息框
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            if (_httpListener?.IsListening == true)
                            {
                                MessageBox.Show($"HTTP 服务器处理请求时出错：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                        });
                    }
                });

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"HTTP 服务器启动失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                _httpListener = null; // 启动失败，重置为 null
                return false;
            }
        }

        // 加载 HTML 文件并在浏览器中打开
        private void LoadHtmlAndOpenInBrowser()
        {
            try
            {
                // 自动打开浏览器访问该页面
                Process.Start(new ProcessStartInfo("http://localhost:8000") { UseShellExecute = true });
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开浏览器失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        // 根据文件扩展名获取 MIME 类型
        private string GetMimeType(string extension)
        {
            extension = extension.ToLowerInvariant();

            switch (extension)
            {
                case ".jpg":
                case ".jpeg":
                    return "image/jpeg";
                case ".png":
                    return "image/png";
                case ".gif":
                    return "image/gif";
                case ".bmp":
                    return "image/bmp";
                case ".svg":
                    return "image/svg+xml";
                case ".css":
                    return "text/css";
                case ".js":
                    return "application/javascript";
                default:
                    return "application/octet-stream";
            }
        }
        private void ViewPicButton_Click(object sender, RoutedEventArgs e)
        {
            // 检查保存路径输入框是否为空或仅包含空白字符
            if (string.IsNullOrWhiteSpace(SavePicBox.Text))
            {
                MessageBox.Show("请先选择图片存储路径", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }


            // 定义生成的 HTML 文件完整路径
            string htmlPath = System.IO.Path.Combine(SavePicBox.Text, "screenshot_viewer.html");

            try
            {
                // 用于存储从数据库读取的元数据
                var metaData = new List<Dictionary<string, object>>();
                const string connectionString = "Server=localhost;Port=3306;Database=screenpic;Uid=root;Pwd=hjj1019583787;";

                using (var connection = new MySqlConnection(connectionString))
                {
                    connection.Open();
                    const string query = "SELECT id, file_name, file_path, file_format, capture_width, capture_height, create_time, last_modify_time FROM screenshots";

                    using (var command = new MySqlCommand(query, connection))
                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var record = new Dictionary<string, object>();
                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                record[reader.GetName(i)] = reader.GetValue(i);
                            }
                            metaData.Add(record);
                        }
                    }
                }

                // 复制背景图片到目标目录
                string backgroundSource = @"C:\Users\misaka mikoto\Pictures\BeauTi\ShoreKeeper(1).jpg";
                string backgroundDest = Path.Combine(SavePicBox.Text, "ShoreKeeper(1).jpg");

                if (File.Exists(backgroundSource) && !File.Exists(backgroundDest))
                {
                    try
                    {
                        File.Copy(backgroundSource, backgroundDest);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"复制背景图片失败: {ex.Message}");
                    }
                }
                // 生成 HTML
                var html = new StringBuilder();
                html.AppendLine("<!DOCTYPE html>");
                html.AppendLine("<html lang=\"zh-CN\">");
                html.AppendLine("<head>");
                html.AppendLine("<meta charset=\"UTF-8\">");
                html.AppendLine("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">");
                html.AppendLine("<title>截图查看器</title>");
                html.AppendLine("<script src=\"https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.0/fabric.min.js\"></script>");
                html.AppendLine("<style>");
                html.AppendLine("body {");
                html.AppendLine("    font-family: 'Segoe UI', sans-serif;");
                html.AppendLine("    margin: 20px;");
                html.AppendLine("    background-image: url('images/ShoreKeeper(1).jpg');");
                html.AppendLine("    background-size: cover;");
                html.AppendLine("    background-repeat: no-repeat;");
                html.AppendLine("    background-attachment: fixed;");
                html.AppendLine("    background-position: center;");
                html.AppendLine("}");
                html.AppendLine(".container {");
                html.AppendLine("    max-width: 1200px;");
                html.AppendLine("    margin: 0 auto;");
                html.AppendLine("    background-color: rgba(255, 255, 255, 0.7);");
                html.AppendLine("    padding: 20px;");
                html.AppendLine("    border-radius: 8px;");
                html.AppendLine("    box-shadow: 0 4px 12px rgba(0,0,0,0.15);");
                html.AppendLine("}");
                html.AppendLine(".header { display: flex; flex-direction: column; gap: 15px; align-items: flex-start; margin-bottom: 20px; }");
                html.AppendLine(".search-container { display: flex; gap: 15px; width: 100%; }");
                html.AppendLine("body { font-family: 'Segoe UI', sans-serif; margin: 20px; background-color: #f5f7fa; }");
                html.AppendLine(".container { max-width: 1200px; margin: 0 auto; }");
                html.AppendLine(".header { display: flex; flex-direction: column; gap: 15px; align-items: flex-start; margin-bottom: 20px; }");
                html.AppendLine(".search-container { display: flex; gap: 15px; width: 100%; }");
                html.AppendLine(".search-label { display: flex; align-items: center; gap: 8px; flex: 1; }");
                html.AppendLine(".search-input { flex: 1; padding: 8px 12px; border: 1px solid #e2e8f0; border-radius: 6px; font-size: 0.9em; }");
                html.AppendLine(".sort-options { display: flex; gap: 15px; align-items: center; }");
                html.AppendLine(".sort-label { display: flex; align-items: center; gap: 5px; cursor: pointer; }");
                html.AppendLine(".delete-btn { padding: 6px 12px; background-color: #e53e3e; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 0.85em; transition: background-color 0.2s; }");
                html.AppendLine(".delete-btn:hover { background-color: #c53030; }");
                html.AppendLine(".image-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 20px; }");
                html.AppendLine(".image-card { background: white; padding: 12px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); transition: transform 0.2s ease; position: relative; cursor: pointer; }");
                html.AppendLine(".image-card:hover { transform: translateY(-4px); }");
                html.AppendLine(".image-card .select-checkbox { position: absolute; top: 8px; left: 8px; z-index: 10; }");
                html.AppendLine(".image-preview { width: 100%; height: 200px; object-fit: cover; border-radius: 4px; }");
                html.AppendLine(".file-name { margin: 8px 0 0; color: #4a5568; font-size: 0.9em; text-align: center; overflow: hidden; text-overflow: ellipsis; }");
                html.AppendLine(".file-meta { font-size: 0.8em; color: #718096; text-align: center; margin-top: 4px; }");
                html.AppendLine(".hidden { display: none; }");
                html.AppendLine(".delete-modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); z-index: 100; align-items: center; justify-content: center; }");
                html.AppendLine(".modal-content { background-color: white; padding: 20px; border-radius: 8px; width: 90%; max-width: 400px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); }");
                html.AppendLine(".modal-actions { display: flex; gap: 10px; justify-content: flex-end; margin-top: 15px; }");
                html.AppendLine(".btn { padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer; font-size: 0.9em; }");
                html.AppendLine(".btn-primary { background-color: #2b6cb0; color: white; }");
                html.AppendLine(".btn-danger { background-color: #e53e3e; color: white; }");
                html.AppendLine(".image-detail { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: white; z-index: 200; overflow: auto; }");
                html.AppendLine(".detail-container { display: flex; height: 100%; }");
                html.AppendLine(".detail-sidebar { width: 30%; max-width: 350px; padding: 20px; background: #f8fafc; border-right: 1px solid #e2e8f0; overflow-y: auto; }");
                html.AppendLine(".detail-content { flex: 1; display: flex; align-items: center; justify-content: center; padding: 20px; background: #f0f4f8; }");
                html.AppendLine(".detail-image { max-width: 100%; max-height: 90vh; box-shadow: 0 4px 12px rgba(0,0,0,0.15); }");
                html.AppendLine(".close-btn { position: absolute; top: 15px; right: 15px; font-size: 24px; cursor: pointer; z-index: 10; }");
                html.AppendLine(".meta-item { margin-bottom: 15px; }");
                html.AppendLine(".meta-label { font-weight: 600; color: #4a5568; margin-bottom: 5px; }");
                html.AppendLine(".meta-value { color: #718096; }");
                html.AppendLine("#editTools { display: none; margin-top: 20px; gap: 15px; }");
                html.AppendLine("#editCanvas { background: white; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }");
                html.AppendLine(".edit-window { position: fixed; top:0; left:0; width:100vw; height:100vh; background:white; z-index:300; }");
                html.AppendLine("</style>");
                html.AppendLine("</head>");
                html.AppendLine("<body>");
                html.AppendLine("<div class=\"container\">");
                html.AppendLine("<div class=\"header\">");
                html.AppendLine("<h1 style=\"color: #2d3748; margin: 0; display: inline-block;\">截图列表</h1>");
                html.AppendLine("<button id=\"authorizeBtn\" style=\"margin-left: 15px; padding: 6px 12px; background-color: #4299e1; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 0.85em;\">授予文件操作权限</button>");
                html.AppendLine("<div class=\"search-container\">");
                html.AppendLine("<label class=\"search-label\"><span style=\"color: #4a5568;\">文件名搜索：</span><input type=\"text\" id=\"searchFileName\" class=\"search-input\" placeholder=\"支持正则匹配（如.*截图.*）\"></label>");
                html.AppendLine("<label class=\"search-label\"><span style=\"color: #4a5568;\">时间搜索：</span><input type=\"text\" id=\"searchTime\" class=\"search-input\" placeholder=\"支持正则匹配（如^2025-05-23）\"></label>");
                html.AppendLine("</div>");
                html.AppendLine("<div class=\"sort-options\">");
                html.AppendLine("<label class=\"sort-label\"><input type=\"checkbox\" id=\"sortByName\"><span>按名称排序（升序）</span></label>");
                html.AppendLine("<label class=\"sort-label\"><input type=\"checkbox\" id=\"sortByTime\"><span>按时间排序（最近）</span></label>");
                html.AppendLine("<button id=\"deleteBtn\" class=\"delete-btn\">删除选中</button>");
                html.AppendLine("</div>");
                html.AppendLine("</div>");
                html.AppendLine("<div class=\"image-grid\" id=\"imageGrid\">");
                foreach (var item in metaData)
                {
                    string fileName = item["file_name"].ToString();
                    DateTime createTime = (DateTime)item["create_time"];
                    string filePath = System.IO.Path.Combine(SavePicBox.Text, fileName);
                    string displayTime = createTime.ToString("yyyy-MM-dd HH:mm:ss");
                    string fileFormat = item["file_format"].ToString();
                    int width = (int)item["capture_width"];
                    int height = (int)item["capture_height"];
                    DateTime? modifyTime = item["last_modify_time"] as DateTime?;
                    string modifyTimeStr = modifyTime.HasValue ? modifyTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "未记录";
                    html.AppendLine($"<div class=\"image-card\" data-name=\"{System.Web.HttpUtility.HtmlEncode(fileName)}\" data-time=\"{displayTime}\" data-path=\"images/{System.Web.HttpUtility.HtmlEncode(fileName)}\" data-format=\"{fileFormat}\" data-width=\"{width}\" data-height=\"{height}\" data-modify=\"{modifyTimeStr}\">");
                    html.AppendLine($"<input type=\"checkbox\" class=\"select-checkbox\" data-file=\"{System.Web.HttpUtility.HtmlEncode(fileName)}\">");
                    if (System.IO.File.Exists(filePath))
                    {
                        html.AppendLine($"<img class=\"image-preview\" src=\"images/{fileName}\" alt=\"{System.Web.HttpUtility.HtmlEncode(fileName)}\"/>");
                    }
                    else
                    {
                        html.AppendLine("<div class=\"image-preview\" style=\"background: #f0f4f8; display: flex; align-items: center; justify-content: center;\"><span style=\"color: #a0aec0;\">图片丢失</span></div>");
                    }
                    html.AppendLine($"<div class=\"file-name\">{System.Web.HttpUtility.HtmlEncode(fileName)}</div>");
                    html.AppendLine($"<div class=\"file-meta\">{displayTime} · {fileFormat}</div>");
                    html.AppendLine("</div>");
                }
                html.AppendLine("</div>");
                html.AppendLine("</div>");
                html.AppendLine("<div class=\"delete-modal\" id=\"deleteModal\">");
                html.AppendLine("<div class=\"modal-content\">");
                html.AppendLine("<h3 style=\"color: #2d3748; margin-top: 0;\">确认删除</h3>");
                html.AppendLine("<p>您确定要删除选中的 <span id=\"deleteCount\">0</span> 张图片吗？</p>");
                html.AppendLine("<div class=\"modal-actions\">");
                html.AppendLine("<button id=\"cancelDelete\" class=\"btn\">取消</button>");
                html.AppendLine("<button id=\"confirmDelete\" class=\"btn btn-danger\">删除</button>");
                html.AppendLine("</div>");
                html.AppendLine("</div>");
                html.AppendLine("</div>");
                html.AppendLine("<div class=\"image-detail\" id=\"imageDetail\">");
                html.AppendLine("<span class=\"close-btn\" id=\"closeDetail\">&times;</span>");
                html.AppendLine("<div class=\"detail-container\">");
                html.AppendLine("<div class=\"detail-sidebar\">");
                html.AppendLine("<div class=\"meta-item\"><div class=\"meta-label\">文件名</div><div class=\"meta-value\" id=\"detailName\"></div></div>");
                html.AppendLine("<div class=\"meta-item\"><div class=\"meta-label\">创建时间</div><div class=\"meta-value\" id=\"detailTime\"></div></div>");
                html.AppendLine("<div class=\"meta-item\"><div class=\"meta-label\">文件格式</div><div class=\"meta-value\" id=\"detailFormat\"></div></div>");
                html.AppendLine("<div class=\"meta-item\"><div class=\"meta-label\">文件路径</div><div class=\"meta-value\" id=\"detailPath\"></div></div>");
                html.AppendLine("<div class=\"meta-item\"><div class=\"meta-label\">截图尺寸</div><div class=\"meta-value\" id=\"detailSize\"></div></div>");
                html.AppendLine("<div class=\"meta-item\"><div class=\"meta-label\">最后修改</div><div class=\"meta-value\" id=\"detailModify\"></div></div>");
                html.AppendLine("<div class=\"meta-item\"><button onclick=\"openEditWindow()\" class=\"edit-btn\" style=\"padding: 10px 16px; font-size: 14px;\">在线编辑</button></div>");
                html.AppendLine("</div>");
                html.AppendLine("<div class=\"detail-content\">");
                html.AppendLine("<img id=\"detailImage\" class=\"detail-image\" src=\"\" alt=\"大图预览\" style=\"display:block;\">");
                html.AppendLine("<canvas id=\"editCanvas\" style=\"display:none;\"></canvas>");
                html.AppendLine("</div>");
                html.AppendLine("</div>");
                html.AppendLine("</div>");
                html.AppendLine("<div id=\"editWindow\" class=\"edit-window\" style=\"display:none;\">");
                html.AppendLine("<div style=\"display:flex;height:100vh;\">");
                html.AppendLine("<div style=\"width:200px;padding:20px;background:#f8fafc;border-right:1px solid #e2e8f0; display: flex; flex-direction: column; gap: 15px;\">");
                html.AppendLine("<div style=\"display: flex; align-items: center; gap: 10px;\">");
                html.AppendLine("<span style=\"font-size: 14px;\">画笔颜色:</span>");
                html.AppendLine("<input type=\"color\" id=\"editColor\" style=\"height: 40px; width: 40px;\">");
                html.AppendLine("</div>");
                html.AppendLine("<div style=\"display: flex; align-items: center; gap: 10px;\">");
                html.AppendLine("<span style=\"font-size: 14px;\">画笔大小:</span>");
                html.AppendLine("<input type=\"range\" id=\"editSize\" min=\"1\" max=\"20\" value=\"5\" style=\"flex: 1; height: 40px;\">");
                html.AppendLine("</div>");
                html.AppendLine("<button onclick=\"setEditTool('pencil')\" style=\"padding: 12px 20px; font-size: 14px;\">画笔</button>");
                html.AppendLine("<button onclick=\"setEditTool('text')\" style=\"padding: 12px 20px; font-size: 14px;\">文字</button>");
                html.AppendLine("<button onclick=\"setEditTool('rect')\" style=\"padding: 12px 20px; font-size: 14px;\">矩形</button>");
                html.AppendLine("<button onclick=\"saveEdit()\" style=\"padding: 12px 20px; font-size: 14px; background-color: #2b6cb0; color: white;\">保存图片</button>");
                html.AppendLine("<button onclick=\"downloadOpenDrawFile()\" style=\"padding: 12px 20px; font-size: 14px;\">更多编辑</button>");
                html.AppendLine("<button onclick=\"closeEdit()\" style=\"padding: 12px 20px; font-size: 14px; background-color: #64748b; color: white;\">关闭</button>");
                html.AppendLine("</div>");
                html.AppendLine("<canvas id=\"mainCanvas\" style=\"flex:1;\"></canvas>");
                html.AppendLine("</div>");
                html.AppendLine("</div>");
                html.AppendLine("<script>");
                html.AppendLine("const searchFileName = document.getElementById('searchFileName'),");
                html.AppendLine("      searchTime = document.getElementById('searchTime'),");
                html.AppendLine("      sortByName = document.getElementById('sortByName'),");
                html.AppendLine("      sortByTime = document.getElementById('sortByTime'),");
                html.AppendLine("      imageGrid = document.getElementById('imageGrid'),");
                html.AppendLine("      deleteBtn = document.getElementById('deleteBtn'),");
                html.AppendLine("      deleteModal = document.getElementById('deleteModal'),");
                html.AppendLine("      deleteCount = document.getElementById('deleteCount'),");
                html.AppendLine("      cancelDelete = document.getElementById('cancelDelete'),");
                html.AppendLine("      confirmDelete = document.getElementById('confirmDelete'),");
                html.AppendLine("      authorizeBtn = document.getElementById('authorizeBtn'),");
                html.AppendLine("      imageDetail = document.getElementById('imageDetail'),");
                html.AppendLine("      closeDetail = document.getElementById('closeDetail'),");
                html.AppendLine("      detailName = document.getElementById('detailName'),");
                html.AppendLine("      detailTime = document.getElementById('detailTime'),");
                html.AppendLine("      detailFormat = document.getElementById('detailFormat'),");
                html.AppendLine("      detailPath = document.getElementById('detailPath'),");
                html.AppendLine("      detailSize = document.getElementById('detailSize'),");
                html.AppendLine("      detailModify = document.getElementById('detailModify'),");
                html.AppendLine("      detailImage = document.getElementById('detailImage');");
                html.AppendLine("let selectedFiles = [], authorizedDirHandle = null, editCanvas = null, currentTool = 'pencil';");
                html.AppendLine("function filterAndSortCards() {");
                html.AppendLine("    const cards = Array.from(imageGrid.children),");
                html.AppendLine("          nameRegex = searchFileName.value ? new RegExp(searchFileName.value, 'i') : null,");
                html.AppendLine("          timeRegex = searchTime.value ? new RegExp(searchTime.value, 'i') : null;");
                html.AppendLine("    const filteredCards = cards.filter(card => {");
                html.AppendLine("        const nameMatch = !nameRegex || nameRegex.test(card.dataset.name),");
                html.AppendLine("              timeMatch = !timeRegex || timeRegex.test(card.dataset.time);");
                html.AppendLine("        return nameMatch && timeMatch;");
                html.AppendLine("    });");
                html.AppendLine("    filteredCards.sort((a, b) => {");
                html.AppendLine("        if (sortByName.checked) return a.dataset.name.localeCompare(b.dataset.name);");
                html.AppendLine("        if (sortByTime.checked) return new Date(b.dataset.time) - new Date(a.dataset.time);");
                html.AppendLine("        return 0;");
                html.AppendLine("    });");
                html.AppendLine("    cards.forEach(card => card.classList.add('hidden'));");
                html.AppendLine("    filteredCards.forEach(card => {");
                html.AppendLine("        card.classList.remove('hidden');");
                html.AppendLine("        imageGrid.appendChild(card);");
                html.AppendLine("    });");
                html.AppendLine("    updateDeleteButtonState();");
                html.AppendLine("}");
                html.AppendLine("function updateDeleteButtonState() {");
                html.AppendLine("    const selected = document.querySelectorAll('.select-checkbox:checked');");
                html.AppendLine("    deleteBtn.disabled = selected.length === 0;");
                html.AppendLine("    deleteBtn.style.opacity = selected.length === 0 ? '0.5' : '1';");
                html.AppendLine("}");
                html.AppendLine("function showImageDetail(card) {");
                html.AppendLine("    detailName.textContent = card.dataset.name;");
                html.AppendLine("    detailTime.textContent = card.dataset.time;");
                html.AppendLine("    detailFormat.textContent = card.dataset.format;");
                html.AppendLine("    detailPath.textContent = card.dataset.path;");
                html.AppendLine("    detailSize.textContent = `${card.dataset.width} × ${card.dataset.height} 像素`;");
                html.AppendLine("    detailModify.textContent = card.dataset.modify;");
                html.AppendLine("    detailImage.src = card.querySelector('.image-preview').src;");
                html.AppendLine("    imageDetail.style.display = 'block';");
                html.AppendLine("}");
                html.AppendLine("async function saveEditedImage() {");
                html.AppendLine("    if (!authorizedDirHandle) {");
                html.AppendLine("        alert('请先授予文件操作权限');");
                html.AppendLine("        return;");
                html.AppendLine("    }");
                html.AppendLine("    const dataUrl = editCanvas.toDataURL({ format: 'png' });");
                html.AppendLine("    const blob = await (await fetch(dataUrl)).blob();");
                html.AppendLine("    const fileName = 'C' + detailName.textContent;");
                html.AppendLine("    const fileHandle = await authorizedDirHandle.getFileHandle(fileName, { create: true });");
                html.AppendLine("    const writable = await fileHandle.createWritable();");
                html.AppendLine("    await writable.write(blob);");
                html.AppendLine("    await writable.close();");
                html.AppendLine("    alert('图片已保存到授权目录');");
                html.AppendLine("}");
                html.AppendLine("authorizeBtn.addEventListener('click', async () => {");
                html.AppendLine("    try {");
                html.AppendLine("        const dirHandle = await window.showDirectoryPicker({ startIn: 'desktop' });");
                html.AppendLine("        authorizedDirHandle = dirHandle;");
                html.AppendLine("        alert('已授权保存路径');");
                html.AppendLine("    } catch (e) {");
                html.AppendLine("        console.error('授权失败', e);");
                html.AppendLine("        alert('授权操作已取消');");
                html.AppendLine("    }");
                html.AppendLine("});");
                html.AppendLine("deleteBtn.addEventListener('click', () => {");
                html.AppendLine("    const selectedCheckboxes = document.querySelectorAll('.select-checkbox:checked');");
                html.AppendLine("    if (selectedCheckboxes.length === 0) return;");
                html.AppendLine("    selectedFiles = Array.from(selectedCheckboxes).map(checkbox => {");
                html.AppendLine("        const card = checkbox.closest('.image-card');");
                html.AppendLine("        return { name: card.dataset.name, path: card.dataset.path };");
                html.AppendLine("    });");
                html.AppendLine("    deleteCount.textContent = selectedFiles.length;");
                html.AppendLine("    deleteModal.style.display = 'flex';");
                html.AppendLine("});");
                html.AppendLine("cancelDelete.addEventListener('click', () => {");
                html.AppendLine("    deleteModal.style.display = 'none';");
                html.AppendLine("    selectedFiles = [];");
                html.AppendLine("});");
                html.AppendLine("confirmDelete.addEventListener('click', async () => {");
                html.AppendLine("    if (selectedFiles.length === 0 || !authorizedDirHandle) {");
                html.AppendLine("        deleteModal.style.display = 'none';");
                html.AppendLine("        return;");
                html.AppendLine("    }");
                html.AppendLine("    const originalText = confirmDelete.textContent;");
                html.AppendLine("    confirmDelete.textContent = '请稍等...';");
                html.AppendLine("    confirmDelete.disabled = true;");
                html.AppendLine("    const timeStr = new Date().toISOString().replace(/[:T]/g, '_').slice(0, 16);");
                html.AppendLine("    const fileNames = selectedFiles.map(f => f.name).join('\\n');");
                html.AppendLine("    try {");
                html.AppendLine("        const fileHandle = await authorizedDirHandle.getFileHandle(`删除记录${timeStr}.txt`, { create: true });");
                html.AppendLine("        const writable = await fileHandle.createWritable();");
                html.AppendLine("        await writable.write(fileNames);");
                html.AppendLine("        await writable.close();");
                html.AppendLine("        await new Promise(resolve => setTimeout(resolve, 2000));");
                html.AppendLine("        selectedFiles.forEach(file => {");
                html.AppendLine("            const card = document.querySelector(`.image-card[data-name=\"${file.name}\"]`);");
                html.AppendLine("            card && card.remove();");
                html.AppendLine("        });");
                html.AppendLine("        deleteModal.style.display = 'none';");
                html.AppendLine("        selectedFiles = [];");
                html.AppendLine("        updateDeleteButtonState();");
                html.AppendLine("        confirmDelete.textContent = originalText;");
                html.AppendLine("        confirmDelete.disabled = false;");
                html.AppendLine("        alert('删除操作已完成');");
                html.AppendLine("    } catch (e) {");
                html.AppendLine("        console.error('保存失败', e);");
                html.AppendLine("        confirmDelete.textContent = originalText;");
                html.AppendLine("        confirmDelete.disabled = false;");
                html.AppendLine("        alert('记录保存失败，请检查授权路径');");
                html.AppendLine("    }");
                html.AppendLine("});");
                html.AppendLine("imageGrid.addEventListener('change', e => {");
                html.AppendLine("    e.target.classList.contains('select-checkbox') && updateDeleteButtonState();");
                html.AppendLine("});");
                html.AppendLine("imageGrid.addEventListener('click', e => {");
                html.AppendLine("    const card = e.target.closest('.image-card');");
                html.AppendLine("    if (card && !e.target.classList.contains('select-checkbox')) showImageDetail(card);");
                html.AppendLine("});");
                html.AppendLine("closeDetail.addEventListener('click', () => {");
                html.AppendLine("    imageDetail.style.display = 'none';");
                html.AppendLine("});");
                html.AppendLine("[searchFileName, searchTime].forEach(input => {");
                html.AppendLine("    input.addEventListener('input', () => {");
                html.AppendLine("        sortByName.checked = false;");
                html.AppendLine("        sortByTime.checked = false;");
                html.AppendLine("        filterAndSortCards();");
                html.AppendLine("    });");
                html.AppendLine("});");
                html.AppendLine("[sortByName, sortByTime].forEach(checkbox => {");
                html.AppendLine("    checkbox.addEventListener('change', e => {");
                html.AppendLine("        if (e.target.checked) {");
                html.AppendLine("            const otherCheckbox = e.target === sortByName ? sortByTime : sortByName;");
                html.AppendLine("            otherCheckbox.checked = false;");
                html.AppendLine("        }");
                html.AppendLine("        filterAndSortCards();");
                html.AppendLine("    });");
                html.AppendLine("});");
                html.AppendLine("</script>");
                html.AppendLine("<script>");
                html.AppendLine("let currentImageInfo = null;");
                html.AppendLine("function openEditWindow() {");
                html.AppendLine("    const editWindow = document.getElementById('editWindow');");
                html.AppendLine("    editWindow.style.display = 'block';");
                html.AppendLine("    currentImageInfo = {");
                html.AppendLine("        name: detailName.textContent,");
                html.AppendLine("        path: detailPath.textContent,");
                html.AppendLine("        src: detailImage.src");
                html.AppendLine("    };");
                html.AppendLine("    const canvasEl = document.getElementById('mainCanvas');");
                html.AppendLine("    canvasEl.width = detailImage.naturalWidth;");
                html.AppendLine("    canvasEl.height = detailImage.naturalHeight;");
                html.AppendLine("    editCanvas = new fabric.Canvas('mainCanvas', {");
                html.AppendLine("        isDrawingMode: true,");
                html.AppendLine("        selection: false");
                html.AppendLine("    });");
                html.AppendLine("    fabric.Image.fromURL(currentImageInfo.src, img => {");
                html.AppendLine("        img.set({");
                html.AppendLine("            left: 0,");
                html.AppendLine("            top: 0,");
                html.AppendLine("            selectable: false,");
                html.AppendLine("            evented: false,");
                html.AppendLine("            hasControls: false,");
                html.AppendLine("            hasBorders: false");
                html.AppendLine("        });");
                html.AppendLine("        editCanvas.add(img);");
                html.AppendLine("        editCanvas.sendToBack(img);");
                html.AppendLine("        editCanvas.on('mouse:down', opt => {");
                html.AppendLine("            if (currentTool === 'rect') {");
                html.AppendLine("                const rect = new fabric.Rect({");
                html.AppendLine("                    left: opt.e.offsetX,");
                html.AppendLine("                    top: opt.e.offsetY,");
                html.AppendLine("                    fill: 'transparent',");
                html.AppendLine("                    stroke: document.getElementById('editColor').value,");
                html.AppendLine("                    strokeWidth: document.getElementById('editSize').value");
                html.AppendLine("                });");
                html.AppendLine("                editCanvas.add(rect);");
                html.AppendLine("            } else if (currentTool === 'text') {");
                html.AppendLine("                const text = new fabric.IText('输入文字', {");
                html.AppendLine("                    left: opt.e.offsetX,");
                html.AppendLine("                    top: opt.e.offsetY,");
                html.AppendLine("                    fill: document.getElementById('editColor').value,");
                html.AppendLine("                    fontSize: 20");
                html.AppendLine("                });");
                html.AppendLine("                editCanvas.add(text);");
                html.AppendLine("                text.enterEditing();");
                html.AppendLine("                text.inputElement.addEventListener('keydown', function(e) {");
                html.AppendLine("                    if (e.key === 'Enter') {");
                html.AppendLine("                        e.preventDefault();");
                html.AppendLine("                        text.exitEditing();");
                html.AppendLine("                    }");
                html.AppendLine("                });");
                html.AppendLine("            }");
                html.AppendLine("        });");
                html.AppendLine("    });");
                html.AppendLine("}");
                html.AppendLine("function setEditTool(tool) {");
                html.AppendLine("    editCanvas.isDrawingMode = tool === 'pencil';");
                html.AppendLine("    currentTool = tool;");
                html.AppendLine("}");
                html.AppendLine("async function saveEdit() {");
                html.AppendLine("    if (!authorizedDirHandle) {");
                html.AppendLine("        alert('请先授予文件操作权限');");
                html.AppendLine("        return;");
                html.AppendLine("    }");
                html.AppendLine("    const dataUrl = editCanvas.toDataURL({ format: 'png' });");
                html.AppendLine("    const blob = await (await fetch(dataUrl)).blob();");
                html.AppendLine("    const fileName = 'C' + currentImageInfo.name;");
                html.AppendLine("    const fileHandle = await authorizedDirHandle.getFileHandle(fileName, { create: true });");
                html.AppendLine("    const writable = await fileHandle.createWritable();");
                html.AppendLine("    await writable.write(blob);");
                html.AppendLine("    await writable.close();");
                html.AppendLine("    alert('图片已保存到授权目录');");
                html.AppendLine("}");
                html.AppendLine("function closeEdit() {");
                html.AppendLine("    document.getElementById('editWindow').style.display = 'none';");
                html.AppendLine("    if (editCanvas) {");
                html.AppendLine("        editCanvas.dispose();");
                html.AppendLine("        editCanvas = null;");
                html.AppendLine("    }");
                html.AppendLine("    currentImageInfo = null;");
                html.AppendLine("}");
                html.AppendLine("async function downloadOpenDrawFile() {");
                html.AppendLine("    if (!authorizedDirHandle) {");
                html.AppendLine("        alert('请先授予文件操作权限');");
                html.AppendLine("        return;");
                html.AppendLine("    }");
                html.AppendLine("    if (!currentImageInfo) {");
                html.AppendLine("        alert('没有正在编辑的图片');");
                html.AppendLine("        return;");
                html.AppendLine("    }");
                html.AppendLine("    try {");
                html.AppendLine("        const fileHandle = await authorizedDirHandle.getFileHandle('OpenDraw.txt', { create: true });");
                html.AppendLine("        const writable = await fileHandle.createWritable();");
                html.AppendLine("        await writable.write(currentImageInfo.name);");
                html.AppendLine("        await writable.close();");
                html.AppendLine("        alert('请稍等...');");
                html.AppendLine("    } catch (e) {");
                html.AppendLine("        console.error('创建文件失败', e);");
                html.AppendLine("        alert('创建文件失败，请检查授权路径');");
                html.AppendLine("    }");
                html.AppendLine("}");
                html.AppendLine("document.getElementById('editColor').addEventListener('change', e => {");
                html.AppendLine("    editCanvas.freeDrawingBrush.color = e.target.value;");
                html.AppendLine("});");
                html.AppendLine("document.getElementById('editSize').addEventListener('input', e => {");
                html.AppendLine("    editCanvas.freeDrawingBrush.width = parseInt(e.target.value);");
                html.AppendLine("});");
                html.AppendLine("</script>");
                html.AppendLine("</body>");
                html.AppendLine("</html>");

                System.IO.File.WriteAllText(htmlPath, html.ToString());

               

                // 启动线程检测删除记录
                string monitorPath = SavePicBox.Text;

                if (string.IsNullOrEmpty(monitorPath))
                {
                    MessageBox.Show("请先设置监控路径", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                if (!Directory.Exists(monitorPath))
                {
                    MessageBox.Show($"监控路径不存在: {monitorPath}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                // 停止可能存在的旧监控实例（避免资源泄漏）
                if (_fileMonitor != null)
                {
                    try
                    {
                        _fileMonitor.StopMonitoring();
                        _fileMonitor = null; // 释放旧实例引用
                        Console.WriteLine("已停止旧文件监控实例");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"停止旧监控时出错: {ex.Message}");
                    }
                }
                // 初始化并启动新的文件监控
                _fileMonitor = new RealTimeFileMonitor(monitorPath, SavePicBox.Text);
                _fileMonitor.StartMonitoring();
               // Console.WriteLine($"新文件监控已启动，监控路径: {monitorPath}");

                // 确保服务器运行，只在第一次调用时创建服务器
                if (EnsureHttpServerRunning(htmlPath, SavePicBox.Text))
                {
                    // 服务器已启动，打开浏览器
                    LoadHtmlAndOpenInBrowser();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"生成查看页面失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}